package cn.xuewenbao.ucenter.controller;

import cn.hutool.core.util.RandomUtil;
import cn.xuewenbao.ucenter.entity.Member;
import cn.xuewenbao.ucenter.entity.MemberData;
import cn.xuewenbao.ucenter.entity.vo.MemberLogin;
import cn.xuewenbao.ucenter.entity.vo.RegisterVo;
import cn.xuewenbao.ucenter.service.MemberDataService;
import cn.xuewenbao.ucenter.service.MemberService;
import cn.xuewenbao.ucenter.service.MsmService;
import cn.xuewenbao.ucenter.utils.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/ucenter")
@Api(tags = "前台登录")
@Slf4j
public class LoginFrontEndController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private BaseCommonService baseCommonService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MsmService msmService;

    @Autowired
    private MemberDataService dataService;

    @ApiOperation(value = "前台登录-手机号密码登录")
    @PostMapping("mLogin")
    public Result<JSONObject> loginUser(@RequestBody MemberLogin memberLogin) {
        Result<JSONObject> result = memberService.login(memberLogin);
        return result;
    }

    //注册时确认密码
    @ApiOperation(value = "注册时确认密码")
    @PostMapping("register")
    public Result<JSONObject> register(@RequestBody RegisterVo registerVo){
        Result<JSONObject> result = memberService.register(registerVo);
        return result;
    }

//    @ApiOperation(value = "短信登录")
//    @PostMapping(value = "/smsLogin")
//    public Result<String> sms(@RequestBody JSONObject jsonObject) {
//        Result<String> result = new Result<String>();
//        String mobile = jsonObject.get("mobile").toString();
//        //手机号模式 登录模式: "2"  注册模式: "1"
//        String smsmode = jsonObject.get("smsmode").toString();
//        log.info(mobile);
//        if (oConvertUtils.isEmpty(mobile)) {
//            result.setMessage("手机号不允许为空！");
//            result.setSuccess(false);
//            return result;
//        }
//        Object object = redisUtil.get(mobile);
//        if (object != null) {
//            result.setMessage("验证码10分钟内，仍然有效！");
//            result.setSuccess(false);
//            return result;
//        }
//
//        //随机数
//        String captcha = RandomUtil.randomNumbers(6);
//        JSONObject obj = new JSONObject();
//        obj.put("code", captcha);
//        try {
//            boolean b = false;
//            //注册模板
//            if (CommonConstant.SMS_TPL_TYPE_1.equals(smsmode)) {
//                Member member = memberService.getUserByPhone(mobile);
//                if (member != null) {
//                    result.error500(" 手机号已经注册，请直接登录！");
//                    baseCommonService.addLog("手机号已经注册，请直接登录！", CommonConstant.LOG_TYPE_1, null);
//                    return result;
//                }
//                b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.REGISTER_TEMPLATE_CODE);
//            } else {
//                //登录模式，校验用户有效性
//                Member member = memberService.getUserByPhone(mobile);
//                result = memberService.checkUserEffective(member);
//                if (!result.isSuccess()) {
//                    String message = result.getMessage();
//                    if ("该用户不存在，请注册".equals(message)) {
//                        result.error500("该用户不存在或未绑定手机号");
//                    }
//                    return result;
//                }
//
//                /**
//                 * smsmode 短信模板方式  0 .登录模板、1.注册模板、2.忘记密码模板
//                 */
//                if (CommonConstant.SMS_TPL_TYPE_0.equals(smsmode)) {
//                    //登录模板
//                    b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.LOGIN_TEMPLATE_CODE);
//                } else if (CommonConstant.SMS_TPL_TYPE_2.equals(smsmode)) {
//                    //忘记密码模板
//                    b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE);
//                }
//            }
//
//            if (b == false) {
//                result.setMessage("短信验证码发送失败,请稍后重试");
//                result.setSuccess(false);
//                return result;
//            }
//            //验证码10分钟内有效
//            redisUtil.set(mobile, captcha, 600);
//            //update-begin--Author:scott  Date:20190812 for：issues#391
//            //result.setResult(captcha);
//            //update-end--Author:scott  Date:20190812 for：issues#391
//            result.setSuccess(true);
//
//        } catch (ClientException e) {
//            e.printStackTrace();
//            result.error500(" 短信接口未配置，请联系管理员！");
//            return result;
//        }
//        return result;
//    }

    @ApiOperation(value = "前台登录-退出登录")
    @GetMapping(value = "logout")
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        //用户退出逻辑
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (oConvertUtils.isEmpty(token)) {
            return Result.error("退出登录失败！");
        }
        String mobile = JwtUtils.getMobile(token);
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        Member member = memberService.getOne(wrapper);
        if (member != null) {
            baseCommonService.addLog("用户名: " + member.getUsername() + ",退出成功！", CommonConstant.LOG_TYPE_1, null);
            log.info(" 用户名:  " + member.getUsername() + ",退出成功！ ");
            //清空用户登录Token缓存
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
            //调用shiro的logout
            SecurityUtils.getSubject().logout();
            return Result.ok("退出登录成功！");
        } else {
            return Result.error("Token无效!");
        }
    }

    //发送短信验证码
    @ApiOperation(value = "发送短信验证码")
    @PostMapping(value = "sendMsm/{mobile}")
    public Result<?> sendMsm(@PathVariable String mobile) {
        Result<?> result = new Result<>();

        Member member = memberService.getUserByPhone(mobile);
        if (member == null) {
            Member membernew = new Member();
            membernew.setMobile(mobile);
            final val save = memberService.save(membernew);
            if (save == true) {
                member=membernew;
                MemberData memberData=new MemberData();
                memberData.setUserId(member.getId());
                dataService.save(memberData);
            } else {
                result.setMessage("用户注册失败");
                result.setSuccess(false);
                return result;
            }
        }

        result = memberService.checkUserEffective(member);

        if(!result.isSuccess()) {
            return result;
        }

        Object object = redisUtil.get(mobile);
        if (object != null) {
            result.setMessage("验证码10分钟内，仍然有效！");
            result.setSuccess(false);
            return result;
        }
        //2 如果redis获取 不到，进行腾讯云发送
        //生成随机值
        //随机数
        String captcha = RandomUtil.randomNumbers(6);
        //调用service发送短信的方法
        boolean isSend = msmService.send(mobile, captcha);
        if (isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisUtil.set(mobile, captcha, 60);
            result.setSuccess(true);
            return result;
        } else {
            result.setSuccess(false);
            return result;
        }
    }

    @ApiOperation(value = "验证码登录")
    @PostMapping(value = "smsLogin")
    public Result<JSONObject> sms(@RequestBody JSONObject jsonObject) {
        Result<JSONObject> result = new Result<>();
        String mobile = jsonObject.get("mobile").toString();
        String smsmode = jsonObject.get("smsmode").toString();
        log.info(mobile);
        if (oConvertUtils.isEmpty(mobile)) {
            result.setMessage("手机号不允许为空！");
            result.setSuccess(false);
            return result;
        }
        String captcha = (String) redisUtil.get(mobile);
        if (oConvertUtils.isEmpty(captcha)) {
            result.setMessage("验证码已失效！");
            result.setSuccess(false);
            return result;
        }
        if (!smsmode.equals(captcha)) {
            result.setMessage("验证码错误！");
            result.setSuccess(false);
            return result;
        }
        Member member = memberService.getUserByPhone(mobile);

//        result = memberServiceImpl.checkUserIsEffective(member);

        JSONObject obj = new JSONObject();
        //用户登录信息
        obj.put("userInfo", member);
        if (oConvertUtils.isEmpty(member.getPassword())){
            obj.put("isNew",true);
        }
        // 生成token
        String token = JwtUtils.sign(mobile, captcha);
        // 设置超时时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtils.EXPIRE_TIME*2 / 1000);

        //token 信息
        obj.put("token", token);
        result.setResult(obj);
        result.setSuccess(true);
        result.setCode(200);
        baseCommonService.addLog("手机号: " + mobile + ",登录成功[移动端]！", CommonConstant.LOG_TYPE_1, null);
        return result;
    }

}